/**
 * @describe 音乐
 * @author 游金宇(KM)
 * @date 2023-02-14 14:41:11
 */
import { AudioClip, AudioSource, error, _decorator } from 'cc';
import { CommonAudio } from './CommonAudio';
const { ccclass, menu } = _decorator;

/** 背景音乐 */
export class AudioMusic extends CommonAudio {
    /** 背景音乐播放完成回调 */
    onComplete: Function | null = null;

    private _progress: number = 0;
    public _url: string = null!;
    private _isPlay: boolean = false;

    /** 获取音乐播放进度 */
    get progress(): number {
        if (this.duration > 0) this._progress = this.currentTime / this.duration;
        return this._progress;
    }
    /**
     * 设置音乐当前播放进度
     * @param value     进度百分比0到1之间
     */
    set progress(value: number) {
        this._progress = value;
        this.currentTime = value * this.duration;
    }

    /**
     * 加载音乐并播放
     * @param url          音乐资源地址
     * @param callback     加载完成回调
     */
    load(bundleName: string, url: string): Promise<AudioClip>
    load(url: string): Promise<AudioClip>
    load(arg1: string, arg2?: string) {
        return new Promise((resolve, reject) => {

            let bundleName: string | null = null;
            let url: string;

            if (arg2 !== undefined) {
                bundleName = arg1;
                url = arg2;
            } else {
                url = arg1;
            }

            const cb = (err: Error | null, data: AudioClip) => {
                if (err) {
                    error(err);
                    return reject(err);
                }
                if (this.playing) {
                    this._isPlay = false;
                    this.stop();
                    this.cat.res.release(this._url);
                }

                this.playOnAwake = false
                this.enabled = true;
                this.clip = data;
                this._url = url;

                resolve(data)
            }

            bundleName
                ? this.cat.res.load(bundleName, url, AudioClip, cb)
                : this.cat.res.load(url, AudioClip, cb)
        })
    }

    /** cc.Component 生命周期方法，验证背景音乐播放完成逻辑，建议不要主动调用 */
    override  update(dt: number) {
        if (this.currentTime > 0) {
            this._isPlay = true;
        }

        if (this._isPlay && this.playing == false) {
            this._isPlay = false;
            this.enabled = false;
            this.onComplete && this.onComplete();
        }
    }

    /** 释放当前背景音乐资源 */
    release() {
        if (this._url) {
            this.cat.res.release(this._url);
            this._url = null!;
        }
    }
}
